#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2014-06-17 23:04:35
# @Author  : shitao.tommy (hero007asd@gmail.com)
# @Link    : http://example.org
# @Version : $Id$

from tornado.web import RequestHandler
from tornado.web import addslash
from lib.session import Session
# from lib.mixin import FlashMessagesMixin
from lib import log
from lib.libjson import to_json

from framework.minirest import auth
from lib.libjson import to_json,to_utf8_json
from lib import libtime
import traceback

# from tornado_mysql import pools, connect
from framework.db import conf


from tornado import gen
from tornado.web import asynchronous
import json
# from tornado import gen
# from tornado.web import asynchronous


class BaseHandler(RequestHandler):
    @asynchronous
    @gen.coroutine
    def get(self):
        return self.write_error(404)

    @asynchronous
    @gen.coroutine
    def post(self):
        return self.write_error(404)

    # def render_404(self):
    #     # return self.write_error(404)
    #     return self.render_page("index/404.html")

#TODO ========================生产环境开启===========================
    # def write_error(self, status_code, **kwargs):
    #     if status_code == 404:
    #         # return self.write("404")
    #         return self.render("index/404.html")
    #     elif status_code == 500:
    #         return self.write("500")
    #     else:
    #         return self.write("error:"+ str(status_code))


    def initialize(self):
        self.school_id = 1
        self.offset = 10
        #初始化db连接池

    def prepare(self):
        #打开数据库连接
        # self.conn = pymysql.connect(host=conf.host, port=3306, user=conf.user, passwd=conf.passwd, db=conf.database,charset='utf8')
        pass

    def del_scookie(self, key):
        session = self.get_scookie()
        ret = session.pop(key)
        self.set_secure_cookie('CSESSION', json.dumps(session))
        return ret

    def set_scookie(self, key, name):
        session = self.get_scookie()
        session[key] = name
        self.set_secure_cookie('CSESSION', json.dumps(session))

    def get_scookie(self):
        session = self.get_secure_cookie('CSESSION')
        if not session:
            session = '{}'
        session = json.loads(session)
        return session

    def on_finish(self):
        #关闭数据库连接
        # self.conn.close()

        # cost_time = libtime.get_now_timestamp() - self.start_time
        cost_time = int(self.request.request_time() * 1000)
        # if len(str(self.result)) > 500:
        #     resp_ret = str(len(str(self.result)))
        # else: resp_ret = to_utf8_json(self.result)

        if hasattr(self,'result'):
            if len(str(self.result)) > 500:
                resp_ret = str(len(str(self.result)))
            else:
                resp_ret = to_utf8_json(self.result)
        else: resp_ret = '0'

        log.log_access(self.get_status(), self.request.method, self.request.uri, self.request.remote_ip, 
            '%sms' % cost_time,self.request.arguments,)

        e = traceback.format_exc()
        if e.strip() != 'None':
            log.log_exception(self.__class__.__name__, e)


    def set_default_headers(self):
        self.clear_header('Server')

    # def render_string(self, template_name, **context):
    #     context.update({
    #         'xsrf': self.xsrf_form_html,
    #         'module': self.ui.modules,
    #         'request': self.request,
    #         'user': self.current_user,
    #         'handler': self,}
    #     )

    #     return self._jinja_render(path = self.get_template_path(),filename = template_name,
    #         auto_reload = self.settings['debug'], **context)

    # def _jinja_render(self,path,filename, **context):
    #     template = self.application.jinja_env.get_template(filename,parent=path)
    #     return template.render(**context)

    @property
    def is_xhr(self):
        # print self.request.headers
        return self.request.headers.get('X-Requested-With', '').lower() == 'xmlhttprequest'

    # @property
    # def memcachedb(self):
    #     return self.application.memcachedb

    @property
    def session(self):
        if hasattr(self, '_session'):
            return self._session
        else:
            EXPIRES_DAYS = 1
            sessionid = self.get_secure_cookie('sid')
            self._session = Session(self.application.session_store, sessionid, expires_days=EXPIRES_DAYS)
            if not sessionid:
                self.set_secure_cookie('sid', self._session.id, expires_days=EXPIRES_DAYS)
            return self._session

    # def get_current_user(self):
    #     if hasattr(self.session,'user'):
    #         return self.session['user']
    #     else:
    #         return None

    @property
    def next_url(self):
        return self.get_argument("next", "/")


    def get_distributions(self):
        distributions = self.memcachedb.get('distributions')
        if not distributions:
            distributions = {}
            for distribution in Distribution.select().dicts():
                if distribution['pdid'] == 0:
                    distribution['list'] = []
                    distributions[distribution['id']] = distribution
                else:
                    distributions[distribution['pdid']]['list'].append(distribution)
            self.memcachedb.replace('distributions', distributions, 86400)
        return distributions


    def render_json_success(self):
        pass

    def render_json_fail(self):
        pass

    def render_redirect_login(self):
        if self.is_xhr:
            # render_json
            pass
        else:
            #redirect to route
            pass

    def xhr_success(self, data, msg=''):
        self.result = {'status':200, 'message':msg, 'data':to_json(data)}
        self.write(self.result)

    def xhr_fail(self, data, code=500, msg=''):
        self.result = {'status':code, 'message':msg, 'data':to_json(data)}
        self.write(self.result)

    def xhr_redirect(self, data, url, msg=''):
        '''ajax返回页面跳转'''
        self.result =  {'status':308, 'message':msg, 'url':url, 'data':to_json(data)}
        self.write(self.result)


